package it.polimi.swKnights.SWIMv2.ejb.helpRequest;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerLocal;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.HelpRequest;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.HelpRequestPk;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.RegisteredUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ProcessHelpRequest
 */
@Stateless
public class ProcessHelpRequest implements ProcessHelpRequestRemote
{

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager manager;

	@EJB
	private LoginHandlerLocal loginController;

	@Override
	public void handleAnswerToHelpRequest(String userAsker, String id_request,
			String date_creation, String userHelper, String passwordHelper,
			Boolean accepted) throws LoginFailException,
			InvalidLoginPrivilegesException
	{
		this.loginController.checkLoginDataAndPrivileges(userHelper,
				passwordHelper, RegisteredUser.class);
		this.loginController.checkBanned(userHelper);

		HelpRequestPk helpPK = new HelpRequestPk();
		helpPK.setAnsweringUser(userHelper);
		helpPK.setAskingUser(userAsker);
		try
		{
			helpPK.setId(Integer.parseInt(id_request));
		}
		catch (Exception e)
		{
			throw new IllegalArgumentException(
					" wrong id number, or not a number");
		}

		HelpRequest helpRequest = manager.find(HelpRequest.class, helpPK);

		if (helpRequest == null)
		{
			throw new EntityNotFoundException(
					" something went wrong while finding help request");
		}

		if (accepted == false)
		{
			helpRequest.setAccepted(false);
		}
		else
		{
			helpRequest.setAccepted(true);
		}

	}

}
